package net.onceface.web.oauth2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.onceface.application.dto.ClientDTO;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


/**
 * 
 * **/
public class CustomUserDetails implements UserDetails {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4049226343966891769L;
	
	protected static final String ROLE_PREFIX = "ROLE_";
	
	protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + Privilege.USER.name());

	protected ClientDTO user;
	
	protected String salt;
	
	protected List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
	
	public CustomUserDetails() {
    }
	
	public CustomUserDetails(ClientDTO user) {
		this.user = user;
		initialAuthorities();
    }
	
	private void initialAuthorities() {
		//默认每个人拥有的权限
		this.grantedAuthorities.add(DEFAULT_USER_ROLE);
		//检查盐值是否为空
		if(user.getSalt() != null || "".equals(user.getSalt())){
			this.salt = user.getSalt();
		}
	}

	public String salt(){
		return this.salt;
	}
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		// TODO Auto-generated method stub
		return this.grantedAuthorities;
	}

	@Override
	public String getPassword() {
		// TODO Auto-generated method stub
		return user.getUserPassword();
	}

	@Override
	public String getUsername() {
		// TODO Auto-generated method stub
		return user.getUserAccount();
	}

	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}
	
	public ClientDTO user() {
        return user;
    }
	
	@Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("{user=").append(user);
        sb.append('}');
        return sb.toString();
    }

}
